package com.ymm.controller;

import com.ymm.domain.entity.User;
import com.ymm.domain.entity.UserRole;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.service.UserRoleService;
import com.ymm.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 椰咩咩咩
 * @version 1.0-SNAPSHOT
 * @date 2023/4/8 14:45
 * @Description
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @PreAuthorize("@ps.hasPermission('sys:user:list')")
    @GetMapping("/page")
    public ResponseResult pageUsers(
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(required = false) String name) {
        return userService.pageUsers(pageNum, pageSize, name);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:add')")
    @PostMapping("/add")
    public ResponseResult addUsers(@RequestBody User user) {
        return userService.addUsers(user);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:update')")
    @PutMapping("/update")
    public ResponseResult modifyUser(@RequestBody User user) {
        return userService.modifyUser(user);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:delete')")
    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable Long id) {
        boolean b = userService.removeById(id);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('sys:user:role:assign')")
    @PostMapping("/assign")
    public ResponseResult assignRole(@RequestBody UserRole userRole) {
        userRoleService.save(userRole);
        return ResponseResult.okResult();
    }

    @PreAuthorize("@ps.hasPermission('sys:user:role:delete')")
    @DeleteMapping("/role/delete")
    public ResponseResult deleteRole(@RequestBody UserRole userRole) {
        userRoleService.deleteRoleByUser(userRole);
        return ResponseResult.okResult();
    }

    @PreAuthorize("@ps.hasPermission('user:update:detail')")
    @PutMapping("/update/detail")
    public ResponseResult updateDetail(@RequestBody User user) {
        boolean b = userService.updateById(user);
        return b ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAIL);
    }

    @PreAuthorize("@ps.hasPermission('user:student:list')")
    @GetMapping("/student/list")
    public ResponseResult getStudentList(
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(required = false) String name) {
        return userService.getStudentList(pageNum, pageSize, name);
    }

}
